package com.gopay.checkorder.service.task;

import com.gopay.common.Result;
import com.gopay.common.domain.bank.yspay.expay.pay.YspayAdPayMessage;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.SendMail;
import com.gopay.remote.bank.AdjustInteractRemoteService;
import com.tongtech.wtp.WtpDownloadFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 
 * @ClassName: SpdbAdDownloadOrderTaskImpl 
 * @Description: 代扣下载对账文件 
 * @author ShenJun 
 * @date 2016年11月9日 上午11:43:12
 */
public class SpdbAdDownloadOrderTaskImpl implements Task {
    private final static Logger logger = LoggerFactory.getLogger("CHECK_ORDER");

    @Resource(name = "spdbpayadpayConfig")
    private Map<String, String> spdbpayadpayConfig;

    @Resource(name = "bankAdjustClient")
    private AdjustInteractRemoteService bankAdjustClient;

    @Override
    public void doTask() {
        // 对账单文件名格式：Mer_20160101_99559002.txt
        // 对账单文件夹：/usr/local/ciecc/bankFiles/SPDBPAY/
        // 1.检查文件夹里是否已有昨天对账单文件
        // 2.如果没有则接口查对账单
        // 3.将对账单形成文件放在文件夹里
        // 4.作为附件发送邮件
        logger.error("SpdbpayAdDownloadOrderTaskImpl: 定时任务start ");
        try {
            if ("off".equals(spdbpayadpayConfig.get("mailSwitch"))) {
                logger.error("SpdbpayAdDownloadOrderTaskImpl: 不进行操作直接返回!");
                return;
            }

            // 生成对账单文件所需参数
            String locpath = spdbpayadpayConfig.get("locpath");
            String fTime = DateUtils.getYesterday();
            String reqMerchantNo  = spdbpayadpayConfig.get("merchantNo");
            
            String fName = "Mer_" + fTime + "_" + reqMerchantNo + ".txt";
            List sendFile = new ArrayList();
            List names = new ArrayList();
            String messageText = "";

            //fName = "Mer_20170904_9900000415.txt";
            // 判断本地服务器是否存在代扣对账文件
            if (!(new File(locpath + fName).exists())) {
            	logger.error("SpdbAdDownloadOrderTaskImpl " + fName + " 对账文件不存在!");
            	boolean flag = downloadWTPFile(locpath, fName);
        		if (flag) {
        			names.add(fName);
        		} else {
        			return;
        		}
            } else {
                logger.error("SpdbAdDownloadOrderTaskImpl " + fName + " 对账文件已存在!");
                return;
            }

            // 若对账文件全部为空，则邮件内容标明
            if (names.size() < 1) {
                logger.error("SpdbAdDownloadOrderTaskImpl:浦发代扣对账文件为null或本地已成功下载!");
                return;
            } else {
                messageText = fTime + ":浦发代扣对账文件见附件!" + fName;
                for (int i = 0; i < names.size(); i++) {
                    sendFile.add(locpath + (String) names.get(i));
                }
            }
            String subject = "浦发代扣对账文件";
            String[] cc = spdbpayadpayConfig.get("sendmail.cc").split(","); // 获取多个抄送人
            List ccList = Arrays.asList(cc);

            logger.error("sendMessage  config:--host:"+spdbpayadpayConfig.get("sendmail.host")+"----sender:"+spdbpayadpayConfig.get("sendmail.sender")
            +"----username:"+spdbpayadpayConfig.get("sendmail.username")+"----password:"+spdbpayadpayConfig.get("sendmail.password")
            +"----receiver:"+ spdbpayadpayConfig.get("sendmail.receiver"));
            // 发送邮件
            SendMail.sendMessage(spdbpayadpayConfig.get("sendmail.host"), spdbpayadpayConfig.get("sendmail.sender"),
                    spdbpayadpayConfig.get("sendmail.username"), spdbpayadpayConfig.get("sendmail.password"),
                    spdbpayadpayConfig.get("sendmail.receiver"), subject, messageText, "text/html;charset=gb2312", ccList,
                    sendFile, names);
            logger.error("------浦发代扣发送邮件成功--------");
            
        } catch (Exception e) {
            logger.error("SpdbAdDownloadOrderTaskImpl error: ", e);
        }
    }
    
    public static void main(String argv[])
    {
    	String classpath =  System.getProperty("java.class.path");
    	//System.out.println(System.getProperty("java.library.path"));
    	System.setProperty("java.library.path", "D:\\wtpclient\\lib;D:\\wtpclient\\bin");
    	//System.out.println("====classpath:" + classpath);
    	System.out.println(classpath.indexOf("wtp"));
        WtpDownloadFile download = new WtpDownloadFile();
        download.setOverWrite(true);  // 默认覆盖,
        download.setLocalFileDir(".\\download8"); // 设置

        if ( download.downLoadFile("Mer_20170728_9900000415.txt") !=0  )
            download.printErrorMsg();
                System.out.println("Java:TransId=["+download.getTransId()+"]");                //返回值
                System.out.println("Java:LocalFileName=["+download.getLocalFileName()+"]");      //返回值

        if ( download.downLoadFile("Mer_20170728_9900000415.txt") !=0  )
            download.printErrorMsg();

            System.out.println("Java:TransId=["+download.getTransId()+"]");                //返回值
                System.out.println("Java:LocalFileName=["+download.getLocalFileName()+"]");      //返回值

                 download.setLocalFileDir(null); // 不设置,默认为配置项为准

         if ( download.downLoadFile("15c9aae657","Mer_20170821_9900000415.txt") !=0  )
             download.printErrorMsg();

             System.out.println("Java:TransId=["+download.getTransId()+"]");                //返回值
                 System.out.println("Java:LocalFileName=["+download.getLocalFileName()+"]");      //返回值
     }
    
    private boolean downloadWTPFile(String localFileDir, String localFileName ){
    	WtpDownloadFile download = new WtpDownloadFile();

        download.setOverWrite(true);
        download.setLocalFileDir(localFileDir);
        logger.error("SpdbAdDownloadOrderTaskImpl 对账文件下载 start");
        //从服务器上下载文件文件名为test.java  任务号为1443e513ac的最新文件，注意此处任务id，即为浦发行文件传输平台上配置传输通道的任务id
        if ( download.downLoadFile(spdbpayadpayConfig.get("taskId"),localFileName) !=0  ){
        	download.printErrorMsg();
        	logger.error("SpdbAdDownloadOrderTaskImpl 对账文件下载 end  失败");
        	return false;
        }else{
        	logger.error("SpdbAdDownloadOrderTaskImpl 对账文件下载end   成功");
        	return true;
        }
        

    }

    /**
     * 生成数据文件
     *
     * @param filePath 写入文件的路径
     * @param content  写入的字符串内容
     * @return
     */
    public boolean string2File(String content, String filePath) {
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter;
        boolean flag = true;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            bufferedReader = new BufferedReader(new StringReader(content));
            bufferedWriter = new BufferedWriter(new FileWriter(file));
            char buffer[] = new char[1024];
            int len;
            while ((len = bufferedReader.read(buffer)) != -1) {
                bufferedWriter.write(buffer, 0, len);
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            logger.error(String.valueOf(e));
            flag = false;
            return flag;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    logger.error(String.valueOf(e));
                }
            }
        }
        return flag;
    }
    
    
    
}
